'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const { INTEGER, STRING, DATE, TEXT, ENUM } = Sequelize;
    
    await queryInterface.createTable('collection_records', {
      id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      sales_order_id: {
        type: INTEGER,
        allowNull: false,
        comment: '销售订单ID'
      },
      collection_date: {
        type: DATE,
        allowNull: false,
        comment: '催款日期'
      },
      collection_method: {
        type: ENUM('phone', 'email', 'visit'),
        defaultValue: 'phone',
        comment: '催款方式'
      },
      contact_person: {
        type: STRING(100),
        comment: '联系人'
      },
      response_result: {
        type: TEXT,
        comment: '催款结果'
      },
      next_followup_date: {
        type: DATE,
        comment: '下次跟进日期'
      },
      created_by: {
        type: INTEGER,
        allowNull: false,
        comment: '操作人'
      },
      created_at: {
        type: DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      }
    });

    // 添加索引
    await queryInterface.addIndex('collection_records', ['sales_order_id', 'collection_date'], {
      name: 'collection_records_idx_order_date',
      unique: false
    });

    // 添加外键约束
    await queryInterface.addConstraint('collection_records', {
      fields: ['sales_order_id'],
      type: 'foreign key',
      name: 'fk_collection_records_sales_order_id',
      references: {
        table: 'sales_orders',
        field: 'id'
      },
      onDelete: 'cascade',
      onUpdate: 'cascade'
    });
  },

  down: async (queryInterface, Sequelize) => {
    // 先删除外键约束
    await queryInterface.removeConstraint('collection_records', 'fk_collection_records_sales_order_id');
    
    // 删除索引
    await queryInterface.removeIndex('collection_records', 'collection_records_idx_order_date');
    
    await queryInterface.dropTable('collection_records');
  }
};